/*
 * @Author: Leo Zhang（张吉军）
 * @Description:
 * @需求文档：
 * 高保真：
 * API：
 */

import React, { useEffect, useState } from 'react';
import { Input, Select, Space, Pagination, Button, Spin, Empty } from 'antd';
import { useNavigate, Link, useLocation, useSearchParams } from 'react-router-dom';
import moment from 'moment';
import styles from './style.module.less';
// import testUrl from '@assets/test.png';
import pdfLogo from '@assets/PDF.png';
import mp3Logo from '@assets/mp3.png';
import mp4Logo from '@assets/MP4.png';
import logoUrl from '@assets/logo.jpg';
import baseService from '@service/baseService';
import { divide } from 'lodash';
import app from "../../constant/index";

const { Search } = Input;
const subject = () => {
  const navigate = useNavigate();
  let [searchParams, setSearchParams] = useSearchParams();
  const [activeGradeTab, setActiveGradeTab] = useState<any>('');
  const [activeSortTab, setActiveSortTab] = useState<any>('');
  const [limit, setLimit] = useState(10);
  const [page, setPage] = useState(1);
  const { state } = useLocation();
  const [courseList, setCourseList] = useState<any>([]);
  const [searchResultList, setSearchResultList] = useState([]);
  const [listTotal, setListTotal] = useState(0);
  const [curSubjectId, setCurSubjectId] = useState<any>();
  const [gradeList, setGradeList] = useState([]);
  const [curGrade, setCurGrade] = useState(1);
  const [OrderField, setOrderField] = useState('create_date');
  const [pageLoading, setPageLoading] = useState(false);
  const [downloadLoading, setDownloadLoading] = useState(false);
  const [searchTxt, setSearchTxt] = useState<any>('');

  useEffect(() => {
    // getHotSubjectInfo();
    // 获取科目列表
    handleSubjectList();
    handleGradeList();
  }, []);

  useEffect(() => {
    console.log('jj-curSubjectId', curSubjectId);
    if(curSubjectId) {
      getHotSubjectInfo();
    }
  }, [curSubjectId, activeGradeTab, OrderField, page]);


  useEffect(() => {
    setCurSubjectId(searchParams.get('idx'));
  }, [searchParams.get('idx')]);

  const endswith = (str: any, endStr: any) => {
    str = str.trim()
    let d = str.length - endStr.length
    
    return d >= 0 && str.lastIndexOf(endStr) == d
  }

  const getLogoUrl = (title: any) => {
    if(endswith(title, '.mp3') || endswith(title, '.MP3') || endswith(title, '.Mp3')) {
      return mp3Logo;
    }
    if(endswith(title, '.mp4') || endswith(title, '.MP4') || endswith(title, '.Mp4')) {
      return mp4Logo;
    }
    if(endswith(title, '.pdf') || endswith(title, '.PDF') || endswith(title, '.Pdf')) {
      return pdfLogo;
    }
    return pdfLogo;
  }
  const handleSubjectList = async () => {
    try {
      await baseService.get('/edu/subject/list').then((res: any) => {
        if (res.code == 0) {
          setCourseList(res.data);
        }
      });
    } catch (error) {
      console.log('jj-error', error);
    }
  };

  const handleGradeList = async () => {
    try {
      const res = await baseService.get('/edu/grade/list');
      if (res.code == 0) {
        setGradeList(res.data);
      }
    } catch (error) {
      console.log('jj-error', error);
    }
  };

  const getHotSubjectInfo = () => {
    try {
      setPageLoading(true);
      baseService
        .get(
          `/edu/subject/file/page?subjectId=${curSubjectId}&order=desc&orderField=${OrderField}&page=${page}`
        )
        .then((res: any) => {
          if (res.code == 0) {
            setSearchResultList(res.data?.list);
            setListTotal(res.data?.total);
          }
        })
        .finally(() => {
          setPageLoading(false);
        });
    } catch (error) {}
  };

  const statisticsCount = (type: any, fileId: any) => {
    baseService
      .put(`/edu/subject/file/${type}/${fileId}/count`)
      .then((res: any) => {});
  };
  const handleGradeTabClick = (tabIndex: number, grade: any) => {
    setActiveGradeTab(tabIndex);
    setCurGrade(grade.id);
  };
  const handleSortTabClick = (item: any, tabIndex: number) => {
    setActiveSortTab(tabIndex);
    setOrderField(item.field);
  };

  const SORTLIST = [
    {
      name: '最新',
      field: 'create_date',
    },
    {
      name: '浏览量',
      field: 'view_count ',
    },
    {
      name: '下载量',
      field: 'download_count',
    },
  ];

  const onKeyWordChange = (e: any) => {
    setSearchTxt(e?.target?.value);
  };

  const onSearch = () => {
    navigate('/searchPage', { state: { keyWord: searchTxt } });
  };

  const onChange: any = (page: any) => {
    setPage(page);
  };

  const viewDetail = (event, result: any = {}) => {
    const videoUrl = `${handlePathstr(result?.fileUrl)}`;
    event.stopPropagation();
    statisticsCount(2, result.id);
    navigate('/acticleDetail', { state: { item: result, videoUrl } });
  };

  const handlePathstr = (path) => {
    return path.replace(
      'https://edu-platform-file.oss-cn-hangzhou.aliyuncs.com',
      '/mine'
    );
  };

  const downloadFile = (event, result: any = {}) => {
    setDownloadLoading(true);
    event.stopPropagation();
    statisticsCount(1, result.id);
    // 生成PDF的代码
    const url = 'https://www.example.com/path-to-your-pdf-file.pdf';
    const link = document.createElement('a');
    link.href = handlePathstr(result.fileUrl);
    link.setAttribute('download', result.title);
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    setTimeout(() => {
      setDownloadLoading(false);
    }, 1000);
  };

  return (
    <div className={styles.subjectWrapper}>
      <div className={styles.contentWrapper}>
        {/* <div className={styles.searchBar}>
          <img src={logoUrl} alt="" className={styles.logo} />
          <Search
            placeholder="请输入关键字"
            enterButton="搜索"
            size="large"
            onSearch={onSearch}
            onChange={onKeyWordChange}
            className={styles.searchInput}
            style={{ width: '600px', marginLeft: '100px' }}
          />
        </div>
        <div className={styles.navWrapper}>
          <div className={styles.narMenu}>
            {[{ id: -1, name: '首页' }, ...courseList]?.map(
              (nav: any, idx: any) => {
                return (
                  <div
                    onClick={() => handleTabClick(idx, nav.id)}
                    className={`${styles.narItem} ${
                      activeTab === idx ? styles.narItemActive : ''
                    }`}
                  >
                    {nav.name}
                  </div>
                );
              }
            )}
          </div>
        </div> */}

        {/* <div className={styles.searchParamsWrapper}>
          <span className={styles.label}>年级：</span>
          {gradeList?.map((grade: any, idx: any) => {
            return (
              <span
                onClick={() => handleGradeTabClick(idx, grade)}
                className={`${styles.gradeTxt} ${
                  activeGradeTab == idx ? styles.gradeTxtActive : 0
                }`}
              >
                {grade.name}
              </span>
            );
          })}
        </div> */}

        <div className={styles.resultListWrapper}>
          <div className={styles.sortWrapper}>
            {SORTLIST.map((item, idx) => {
              return (
                <span
                  onClick={() => handleSortTabClick(item, idx)}
                  className={`${styles.sortTxt} ${
                    activeSortTab == idx ? styles.sortTxtActive : 0
                  }`}
                >
                  {item.name}
                </span>
              );
            })}
          </div>
          {searchResultList?.map((result: any) => {
            return (
              <div
                className={styles.searchItem}
                onClick={(e) => viewDetail(e, result)}
              >
                <img src={getLogoUrl(result.title)} alt="" className={styles.logo} />
                {endswith(result.title, '.mp4')}
                <div className={styles.titleWrapper}>
                  <p className={styles.mainTitle}>
                    {result.title?.replace(/\.(mp4|pdf|mp3)$/i, '')}
                  </p>
                  <div className={styles.feature}>
                    <span className={styles.item}>
                      日期: {moment(result.createDate).format('YYYY-MM-DD')}
                    </span>
                    <span className={styles.item}>
                      浏览: {result.viewCount || 0}
                    </span>
                    <span className={styles.item}>
                      下载量: {result.downloadCount}
                    </span>
                  </div>
                </div>
                <div className={styles.actionBtn}>
                  <Button
                    type="primary"
                    style={{ marginBottom: '10px' }}
                    onClick={(e: any) => viewDetail(e, result)}
                  >
                    查看
                  </Button>
                  <Button
                    type="primary"
                    onClick={(e: any) => downloadFile(e, result)}
                  >
                    下载
                  </Button>
                </div>
              </div>
            );
          })}
          {searchResultList.length > 1 && (
            <div className={styles.paginationWrapper}>
              <Pagination
                total={listTotal}
                showSizeChanger
                onChange={onChange}
              />
            </div>
          )}
          {searchResultList.length < 1 && (
            <div className={styles.emptyWrapper}>
              <Empty />
            </div>
          )}
        </div>
      </div>
      <div className={styles.footer_bg}>
        {/* <img src={logoUrl} alt="" className={styles.logo} /> */}
        <section className={styles.footer_section}>
          <p>{app.name} ©2024 版权所有 备案号：< a href="https://beian.miit.gov.cn" target="_blank">苏ICP备2024130913号</a ></p>
        </section>
      </div>
      <Spin size="large" spinning={pageLoading} fullscreen />
      <Spin size="large" tip="下载中" spinning={downloadLoading} fullscreen />
    </div>
  );
};

export default subject;
